<script setup lang="ts">
import { ref, computed, defineExpose } from "vue";
import { useDark, useECharts } from "@pureadmin/utils";
import { getBarLine2 } from "@/api/welcome";

// 兼容dark主题
const { isDark } = useDark();
let theme = computed(() => {
  return isDark.value ? "dark" : "default";
});
// 初始化ECharts
const chartRef = ref();
const { setOptions } = useECharts(chartRef, { theme });
const dataServer = ref([]);
const xAxisData = ref([]);
const getBarLineMEthod = () => {
  getBarLine2().then(res => {
    let { bar, times, line } = res?.data || {};
    xAxisData.value = times;
    let title = ["已使费用", "预算金额"];
    let title1 = ["活动次数", "服务人次"];
    const list = [];

    for (let index = 0; index < title1.length; index++) {
      const element = title1[index];
      list.push({
        name: element,
        type: "line",
        yAxisIndex: index,
        data: line[index],
        smooth: true
      });
    }

    dataServer.value = list;
    renderEcharts(xAxisData.value, dataServer.value);
  });
};
getBarLineMEthod();

defineExpose({
  getBarLineMEthod
});
// 根据配置项渲染ECharts

function renderEcharts(xData, serverData) {
  setOptions({
    legend: {
      bottom: 0
    },
    grid: {
      left: "50px",
      right: "50px",
      top: "50px"
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999"
        }
      },
      formatter: function (params) {
        var res = " ";
        for (var i = 0, l = params.length; i < l; i++) {
          if (i == 0) {
            res += `<strong class='mb-[10px]'>${params[i].axisValueLabel}</strong>`;
          }
          let ratioTitle = "";
          if (params[i].seriesName === "已使费用") {
            ratioTitle = `(<strong style="color:${params[i].color}">${(
              (params[i].value / params[i + 1].value) *
              100
            ).toFixed(2)}%</strong>)`;
          }

          res += `<div>${params[i].marker} ${params[i].seriesName}: ${params[i].value}${ratioTitle}</div>`;
        }
        return res;
      }
    },
    xAxis: [
      {
        type: "category",
        data: xData,
        axisPointer: {
          type: "shadow"
        }
      }
    ],
    yAxis: [
      {
        min: 0,
        boundaryGap: [0, 0.01],
        name: "次数",
        type: "value"
      },
      {
        type: "value",
        name: "人次"
      }
    ],
    series: serverData
  });
}
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 400px" />
</template>
